package services;

import helpers.EmailHelper;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;

import data.EmailData;

import entities.Email;
import entities.Webmail;
import entities.Website;

import models.WebmailModel;
import models.WebsiteModel;

import systems.MailSystem;

public class SendMail extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		//Check send mail
		if (MailSystem.getStatus() == 0) {
			
			List<Email> emails = EmailData.list(MailSystem.getCurrentPage(), MailSystem.getLimit());
			
			WebsiteModel websiteModel = WebsiteModel.getInstance();
			Website website = websiteModel.get(MailSystem.getId());
			if (website != null) {
			
				//Set increate MailSystem
				if (emails.size() == MailSystem.getLimit()) {
					MailSystem.increaseCurrentPage();
					//Set webmail
					WebmailModel webmailModel = WebmailModel.getInstance();
					Webmail webmail = webmailModel.get(MailSystem.getId());
					
					int count = webmail.getCount() + emails.size();
					webmail.setCount(count);
					
					webmailModel.insert(webmail);
				} else {
					MailSystem.setStatus(1);
					
					WebmailModel webmailModel = WebmailModel.getInstance();
					Webmail webmail = webmailModel.get(MailSystem.getId());
					
					int count = webmail.getCount() + emails.size();
					webmail.setCount(count);
					webmail.setStatus(3);
					webmailModel.insert(webmail);
				}
				
				
				
				//Send email
				for (int i = 0; i < emails.size(); i++) {
					//Increase count
					MailSystem.increaseCount();
					
					if (emails.get(i).getStatus() == 1) {
						//send mail
						EmailHelper.sendMailFromUrl(website.getSender(), website.getTitle(), website.getContentUrl(), emails.get(i).getEmail());
					}
				}
			}
		}
		
		response.getWriter().println("Run send mail finish.");
		
	}
}
